package cn.edu.zjut.chopper.registry.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.edu.zjut.chopper.constant.Constant;
import cn.edu.zjut.chopper.registry.Registry;
import cn.edu.zjut.chopper.registry.RegistryContext;
import cn.edu.zjut.chopper.registry.RegistryStatisticsThread;
import cn.edu.zjut.chopper.registry.moniter.Monitor;

/**
 * Servlet implementation class StartRegistry
 */
public class StartRegistry extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Log LOG = LogFactory.getLog(StartRegistry.class);   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public StartRegistry() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			if(RegistryContext.get(Constant.Registry) != null){
				getServletContext().getRequestDispatcher("/error.jsp").forward(
						request, response);
				if(LOG.isErrorEnabled()){
					LOG.error("can not get the registry instance!");
				}
				return;
			}
			Registry registry = new Registry();
			registry.start();
			RegistryContext.put(Constant.Registry,registry);
			Thread monitor = new Monitor();
			monitor.start();
			RegistryContext.put(Constant.RegistryMonitor,monitor);
			Thread statistics = new RegistryStatisticsThread();
			statistics.start();
			RegistryContext.put(Constant.StatisticsThread,statistics);
			getServletContext().getRequestDispatcher("/RemoteInterfaceNameView").forward(
					request, response);
		} catch (IOException e) {
			getServletContext().getRequestDispatcher("/error.jsp").forward(
					request, response);
			if(LOG.isErrorEnabled()){
				LOG.error("can not start the Registry: "+e.getMessage());
			}
			return;
		}
	}

}
